package com.rjwh.dingdong.client.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 项目名称：whrjwh-parent
 * 类描述：
 * 创建人：wby
 * 创建时间：2016/6/27 13:59
 * 修改人：wby
 * 修改时间：2016/6/27 13:59
 * 修改备注：
 *
 */
public class ZipUtils {


    private static final int BUFFER = 1024;

    /**
     * DeCompress the ZIP to the path
     *
     * @param zipFileString name of ZIP
     * @param outPathString path to be unZIP
     * @throws Exception
     */
    public static void UnZipFolder(String zipFileString, String outPathString) {
        File outPath = new File(outPathString);
        if (!outPath.exists()) {
            outPath.mkdir();
        }
        try {
            ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString));
            ZipEntry zipEntry;
            String szName = "";
            while ((zipEntry = inZip.getNextEntry()) != null) {
                szName = zipEntry.getName();
                if (zipEntry.isDirectory()) {
                    // get the folder name of the widget
                    szName = szName.substring(0, szName.length() - 1);
                    File folder = new File(outPathString + File.separator + szName);
                    folder.mkdirs();
                } else {
                    //先判断文件的父级目录是否存在,不存在先创建
                    File file = new File(outPathString + File.separator + szName);
                    File parentDir = file.getParentFile();
                    if (parentDir != null) {
                        if (!parentDir.isDirectory()) {
                            parentDir.mkdirs();
                        }
                    }
                    file.createNewFile();
                    // get the output stream of the file
                    FileOutputStream out = new FileOutputStream(file);
                    int len;
                    byte[] buffer = new byte[BUFFER];
                    // read (len) bytes into buffer
                    while ((len = inZip.read(buffer)) != -1) {
                        // write (len) byte from buffer at the position 0
                        out.write(buffer, 0, len);
                        out.flush();
                    }
                    out.close();
                }
            }
            inZip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
